package com.rykj.api;

import android.database.sqlite.SQLiteException;

import com.google.gson.JsonParseException;
import com.rykj.AppProxy;
import com.rykj.model.entity.ResultBase;
import com.rykj.util.LogX;

import java.io.IOException;

import retrofit2.HttpException;
import rx.Subscriber;

/**
 * description:
 * <p/>
 * Created by 赵六 on 2017/7/17.
 */
public abstract class ResultBaseObservable<T> extends Subscriber<ResultBase<T>> {

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable throwable) {
        String errorMsg = "";
        if (throwable instanceof IOException) {
            errorMsg = "请稍后重试";
        } else if (throwable instanceof HttpException) {
            errorMsg = "请稍后重试";
        } else if (throwable instanceof JsonParseException) {
            errorMsg = "json解析错误";
        } else if (throwable instanceof SQLiteException) {
            errorMsg = "数据库错误";
        } else if (throwable instanceof NullPointerException) {
            errorMsg = "数据异常，稍后重试";
        } else {
            errorMsg = "请稍后重试";
        }
        LogX.e("retrofit", errorMsg + "\n throwable :", throwable);
        onError(errorMsg);
    }

    @Override
    public void onNext(ResultBase<T> result) {
        if (onResponse(result)) {

        } else {
            if (result.code == HttpCode.OK) {
                onSuccess(result.data);
            } else {
                onFail(result.code, result.message);
            }
        }
    }


    /**
     * @param result
     * @return true 拦截后续事件  false 判断成功失败
     */
    public boolean onResponse(ResultBase<T> result) {
        OnErrorCodeIntercept onErrorCodeIntercept = AppProxy.INSTANCE.getOnErrorCodeIntercept();
        if (onErrorCodeIntercept == null) {
            return false;
        } else {
            return onErrorCodeIntercept.onResponse(result.code);
        }
    }

    public abstract void onSuccess(T result);

    public void onFail(int errorCode, String errorMsg) {

    }

    public void onError(String msg) {

    }


}
